package com.zhuxiang.test3;

import java.io.*;

public class CopyDir implements Runnable {
    @Override
    public void run() {
        clone("D:\\a","D:\\1");
        show("D:\\1");
        show("D:\\a");
    }
    public static void show(String path){
        File file = new File(path);
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            return;
        }
        File[] files = file.listFiles();
        for (File f : files){
            System.out.println("该路径下："+ f.getAbsolutePath());
            if (f.isDirectory()){
                show(f.getAbsolutePath());
            }
        }
    }
    public static void clone(String res,String tar){
        File f1 = new File(res);
        File f2 = new File(tar);
        //判断文件不为null或文件目录存在
        if (f1 == null || !f1.exists()){
            System.out.println("拷贝失败");
            return;
        }
        if (f2 == null || !f2.exists()){
            f2.mkdirs();
        }

        //取得源目录下所有的子文件对象
        File[] files = f1.listFiles();
        //遍历该目录下的文件对象
        for (File f : files){
            //判断子目录下是否存在文件
            if (f.isDirectory()){
                clone(f.getAbsolutePath(),tar+"\\"+f.getName());
            }else {
                copyFile(f.getAbsolutePath(),tar+"\\"+f.getName());
            }
        }

    }

    public static void copyFile(String res,String tar){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //文件输入流并进行缓冲
            bis = new BufferedInputStream(new FileInputStream(res));
            //文件输出流并进行缓冲
            bos = new BufferedOutputStream(new FileOutputStream(tar));

            //缓冲数组
            byte[] bytes = new byte[1024*4];
            int len = 0;
            while ((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bos){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null !=bis){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
